import {computed, reactive, ref} from "vue";
import {FetchRDCourseListDAT} from "../../types/responseTypes";
import {getRDCourseList} from "../../api/classes";
import {useStore} from "vuex";

export function useRDCourseList(){

    const courseListWrap = reactive<{
        RDCourseList: FetchRDCourseListDAT[]
    }>({
        RDCourseList: []
    })

    const total = ref(0)
    const {state} = useStore()
    function initRDCourseList(page: number = 1, pageSize: number = 20,params?: Partial<{
        MAJOR_ID: string | number
        COURSENO: string
        COURSENAME: string
        TEACHER_NAME: string
        STATE: '0' | '1'
    }>){
        return new Promise((resolve, reject) => {
            getRDCourseList({
                COURSE_ID: '',
                MAJOR_ID: (params?.MAJOR_ID || '') + '',
                COURSENO: params?.COURSENO || '',
                COURSENAME: params?.COURSENAME || '',
                TEACHER_NAME: params?.TEACHER_NAME || '',
                STATE: params?.STATE || '1',
                PAGEINDEX: page,
                PAGESIZE: pageSize,
                OPERATOR_ID: state.user.userInfo.CUSER_ID
            }).then(res => {
                if (res.ERROR[0].errcode == '0'){
                    courseListWrap.RDCourseList = JSON.parse(JSON.stringify(res.DAT))
                    total.value = res.COUNT[0].NUM
                    resolve(null)
                }else {
                    uni.showToast({
                        title: res.ERROR[0].error,
                        icon: 'none',
                        mask: true
                    })
                    reject('err')
                }
            }).catch(err => {
                uni.showToast({
                    title: '获取列表失败',
                    icon: 'error',
                    mask: true
                })
                reject('err')
            })
        })
    }

    return {
        total,
        RDCourseList: computed(() => courseListWrap.RDCourseList),
        initRDCourseList
    }
}
